package com.ikingtech.framework.sdk.limit.embedded;

import com.ikingtech.framework.sdk.limit.model.RateLimitResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.List;

/**
 * @author zhangqiang
 */
@Slf4j
@RequiredArgsConstructor
public class RateLimiterService {

    private final RedisTemplate<String, Object> redisTemplate;

    private final RedisScript<Long> redisScript;

    public RateLimitResult tryAcquire(String key, Integer count, Integer time) {
        try {
            List<String> keys = Collections.singletonList(key);
            Long execute = this.redisTemplate.execute(this.redisScript, keys, count, time);
            if (execute == null || execute == 0L) {
                RateLimitResult rateLimitResult = new RateLimitResult();
                rateLimitResult.setSuccess(false);
                rateLimitResult.setErrMsg("请求次数过多，请稍后访问");
                return rateLimitResult;
            }
        } catch (Exception e) {
            log.error("限流异常，原因：{}", ExceptionUtils.getStackTrace(e));
            RateLimitResult rateLimitResult = new RateLimitResult();
            rateLimitResult.setErrMsg("限流异常");
            rateLimitResult.setSuccess(false);
            return rateLimitResult;
        }
        RateLimitResult rateLimitResult = new RateLimitResult();
        rateLimitResult.setSuccess(true);
        return rateLimitResult;
    }
}
